package org.example.testcode.helper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description 线程池工具
 */
@Slf4j
public class ThreadPoolHelper {

    private final static int keepAliveTime = 60 * 1000 * 5;
    private final static int workQueue = 500;

    public static ThreadPoolExecutor getFixedThreadPool(int coreSize, String threadName) {
        return getFixedThreadPool(coreSize, workQueue, threadName);
    }

    public static ThreadPoolExecutor getFixedThreadPool(int coreSize, int queuqSize, String threadName) {

        return getThreadPool(coreSize, coreSize, queuqSize, threadName, false);
    }

    public static ThreadPoolExecutor getTempFixedThreadPool(int coreSize, String threadName) {
        return getTempFixedThreadPool(coreSize, workQueue, threadName);
    }

    public static ThreadPoolExecutor getTempFixedThreadPool(int coreSize, int queuqSize, String threadName) {
        return getThreadPool(coreSize, coreSize, queuqSize, threadName, true);
    }

    public static ThreadPoolExecutor getThreadPool(int coreSize, int maxSize, int queuqSize, String threadName, boolean allowCoreThreadTimeOut) {
        return buildThreadPool(coreSize, maxSize, queuqSize, threadName, allowCoreThreadTimeOut);
    }

    private static ThreadPoolExecutor buildThreadPool(int coreSize, int maxSize, int queuqSize, String threadName, boolean allowCoreThreadTimeOut) {
        if (StringUtils.isEmpty(threadName)) {
            throw new RuntimeException("线程池初始化必须有线程名");
        }

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(coreSize, maxSize, keepAliveTime,
                TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queuqSize), new CustomNameThreadFactory(threadName));

        threadPoolExecutor.allowCoreThreadTimeOut(allowCoreThreadTimeOut);

        return threadPoolExecutor;
    }


    public static ScheduledThreadPoolExecutor getSchedulePool(int coreSize, String threadName) {
        if (StringUtils.isEmpty(threadName)) {
            throw new RuntimeException("线程池初始化必须有线程名");
        }
        return new ScheduledThreadPoolExecutor(coreSize, new CustomNameScheduleThreadFactory(threadName));
    }


    //重写自 java.util.concurrent.DefaultThreadFactory
    static class CustomNameThreadFactory implements ThreadFactory {
        //private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;


        CustomNameThreadFactory(String name) {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            namePrefix = name + "-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }

    //重写自 java.util.concurrent.DefaultThreadFactory
    static class CustomNameScheduleThreadFactory implements ThreadFactory {
        //private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;


        CustomNameScheduleThreadFactory(String name) {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            namePrefix = name + "-" + "schedule-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }
}
